<template>
	<view class="tabs">
		<scroll-view id="tab-bar" class="tab-bar" :scroll-x="true" :show-scrollbar="true"
			:scroll-into-view="scrollInto">
			<view style="flex-direction: column;">
				<view style="flex-direction: row;text-align: center;">
					<view class="uni-tab-item" v-for="(tab,index) in tabList" :key="tab.id" :id="tab.id"
						:ref="'tabitem'+index" :data-id="index" :data-current="index" @click="ontabtap">
						<text class="uni-tab-item-title"
							:class="tabIndex==index ? 'uni-tab-item-title-active' : ''">{{tab.name}}</text>
					</view>
				</view>
				<view class="scroll-view-indicator">
					<view ref="underline" class="scroll-view-underline"
						:style="{left: indicatorLineLeft + 'px', width: indicatorLineWidth + 'px'}"></view>
				</view>
			</view>
		</scroll-view>

		<swiper class="tab-view" id="tab-bar-view" :current="tabIndex" :duration="300" @transition="onswiperscroll"
			@animationfinish="animationfinish">
			<swiper-item class="swiper-item" :key="0" style="height: 95%;">
				<view style="text-align: center;" v-if="localRecords.length==0">暂无记录</view>
				<uni-list style="overflow-y: auto;height: 95%;">
					<uni-list-item v-for="(item,index) of localRecords" clickable @click="onClick(item)"
						:title="item.productName" :note="item.createTime"
						:rightText="`${item.moreKeyword }${item.payState}`" />
				</uni-list>

			</swiper-item>
			<swiper-item class="swiper-item" :key="1">
				<view style="height: 95%;">
					<view style="text-align: center;" v-if="mobileRecords.length==0">暂无记录</view>
					<uni-list style="overflow-y: auto;height:95%">
						<uni-list-item v-for="(item,index) of mobileRecords" clickable @click="onClick(item)"
							:title="item.productName" :note="item.createTime"
							:rightText="`${item.moreKeyword }${item.payState}`" />
					</uni-list>

				</view>
				<uni-popup ref="popup" :is-mask-click="false">
					<view id="pop">
						<uni-forms ref="form" :rules="rules" :modelValue="formData">
							<uni-forms-item label="手机号" name="mobile" required>
								<uni-easyinput v-model="formData.mobile" placeholder="请输入手机号" />
							</uni-forms-item>
							<uni-forms-item label="验证码" name="code" required>
								<uni-easyinput type="text" v-model="formData.code" placeholder="请输入验证码"
									style="width: 60%;display: inline-block;" />
								<uni-tag @click="sendCode()" :text="verifyCode.verifyCodeTips" type="primary" />
							</uni-forms-item>
						</uni-forms>
						<view style="text-align: center">
							<button @click="getInfo()" style="width: 60%" type="warn" size="mini">提交</button>
						</view>
					</view>
				</uni-popup>

			</swiper-item>

		</swiper>
	</view>
</template>
<script>
	// #ifdef APP-PLUS
	const dom = weex.requireModule('dom');
	// #endif
	// 缓存页签数量
	const MAX_CACHE_PAGE = 3;
	const TAB_PRELOAD_OFFSET = 1;
	
	import {
		listQuery,
		recordListByMobile
	} from '@/api/jinjian.js'

	import {
		sendVerifyCode
	} from '@/api/login'

	export default {

		data() {
			return {
				scrollInto: "",
				tabIndex: 0,
				cacheTab: [],
				tabList: [{
					id: 'tg',
					name: '本机查询记录'
				}, {
					id: 'dd',
					name: '手机号查询记录'
				}],
				_lastTabIndex: 0,
				indicatorLineLeft: 0,
				indicatorLineWidth: 0,

				index: 0,
				localRecords: [],
				mobileRecords: [],
				onSearchIndex: 0,
				verifyCode: {
					verifyCodeTips: '获取验证码',
					countdown: 60,
				},
				byMobileGet: true,
				formData: {
					mobile: '',
					code: ''
				},
				rules: {
					mobile: {
						rules: [{
							required: true,
							errorMessage: '请填写手机号'
						}, {
							validateFunction: function(rule, value, data, callback) {
								let iphoneReg = (
									/^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/
								); //手机号码
								if (!iphoneReg.test(value)) {
									callback('手机号码格式不正确，请重新填写')
								}
							}
						}]
					},
					code: {
						rules: [{
							required: true,
							errorMessage: '请填写验证码'
						}, {
							format: 'number',
							errorMessage: '验证码为数字'
						}]
					}
				},
			}
		},
		watch: {
			rules(newVal) {
				if (newVal) {
					this.$nextTick(() => {
						this.$refs.rules.setRules(this.rules)
					});
				}
			}
		},
		onLoad() {
			if (localStorage.getItem('sign')) {
				var sign = localStorage.getItem('sign')
				listQuery({
					sign
				}).then(res => {
					this.localRecords = res
				})
			}
		},
		onReady() {
			this._lastTabIndex = 0
			this.swiperWidth = 0
			this.tabbarWidth = 0
			this.tabListSize = {}
			this.selectorQuery()
		},
		methods: {
			settime() {
				if (this.verifyCode.countdown === 1) {
					this.verifyCode.countdown = 60
					this.onSearchIndex = 0
					this.verifyCode.verifyCodeTips = "获取验证码"
					return
				} else {
					this.verifyCode.countdown--
				}
				setTimeout(() => {
					this.verifyCode.verifyCodeTips = "重新获取(" + this.verifyCode.countdown + ")"
					this.settime()
				}, 1000)
			},
			sendCode() {
				var myreg = /^(13[0-9]|14[1579]|15[0-3,5-9]|16[6]|17[0123456789]|18[0-9]|19[89])\d{8}$/
				if (!myreg.test(this.formData.mobile)) {
					this.$modal.msgError('手机号格式错误')
					return
				}
				if (this.onSearchIndex !== 0) {
					return
				}
				this.onSearchIndex = 1
				this.settime()
				sendVerifyCode(this.formData.mobile).then(res => {
					if (res.code == 200) {
						this.$modal.msgSuccess(res.msg)
					}
				})
			},
			getInfo() {
				this.$refs.form.validate().then(res => {
					recordListByMobile(this.formData).then(res => {
						if (res.code == 200) {
							this.mobileRecords = res.data
							this.$refs.popup.close()
							this.byMobileGet = false
						} else {
							this.$modal.msgError(res.msg)
						}
					})
				}).catch(err => {
					console.log('表单错误信息：', err)
				})
			},
			tabClick(index) {
				this.index = index
				if (this.byMobileGet) {
					this.$refs.popup.open('center')
				}
			},
			onClick(item) {
				const index = item.productId
				if (item.payState == '') {
					if (item.productId == 3) { // 企业纳税信息未支付特殊判断
						if (item.moreKeyword.includes('采集成功')) {
							this.$tab.navigateTo('/pages/loading?id=' + item.id)
						} else {
							this.$modal.msg(item.moreKeyword)
						}
					} else {
						this.$modal.msg("输入信息不全或未支付")
					}
				} else {
					this.$tab.navigateTo(`/pages/${this.$path[index]}?orderNo=${item.orderNo}`)
				}
			},
			ontabtap(e) {
				let index = e.target.dataset.current || e.currentTarget.dataset.current;
				// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
				// this.isTap = true;
				var currentSize = this.tabListSize[index];
				this.updateIndicator(currentSize.left, currentSize.width);
				// #endif
				this.switchTab(index);
			},
			onswiperscroll(e) {
				// console.log(e)
				var offsetX = e.detail.dx;
				var preloadIndex = this._lastTabIndex;
				// console.log('---offsetX---', offsetX)
				// console.log('---preloadSize---', preloadIndex)
				if (offsetX > TAB_PRELOAD_OFFSET) {
					preloadIndex++;
				} else if (offsetX < -TAB_PRELOAD_OFFSET) {
					preloadIndex--;
				}
				if (preloadIndex === this._lastTabIndex || preloadIndex < 0) {
					return;
				}
				// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
				var percentage = Math.abs(this.swiperWidth / offsetX);
				var currentSize = this.tabListSize[this._lastTabIndex];
				var preloadSize = this.tabListSize[preloadIndex];
				if (!preloadSize) return

				var lineL = currentSize.left + (preloadSize.left - currentSize.left) / percentage;
				var lineW = currentSize.width + (preloadSize.width - currentSize.width) / percentage;
				this.updateIndicator(lineL, lineW);
				// #endif
			},
			animationfinish(e) {
				// #ifdef APP-PLUS || H5 || MP-WEIXIN || MP-QQ
				let index = e.detail.current;
				this._lastTabIndex = index;
				this.switchTab(index);
				this.tabClick(index)
				this.updateIndicator(this.tabListSize[index].left, this.tabListSize[index].width);
				// #endif
			},
			selectorQuery() {
				// #ifdef APP-NVUE
				// 查询 tabbar 宽度
				uni.createSelectorQuery().in(this).select('#tab-bar').boundingClientRect().exec(rect => {
					this.tabbarWidth = rect[0].width;
				});
				// 查询 tabview 宽度
				uni.createSelectorQuery().in(this).select('#tab-bar-view').boundingClientRect().exec(rect => {
					this.swiperWidth = rect[0].width;
				});
				// 因 nvue 暂不支持 class 查询
				var queryTabSize = uni.createSelectorQuery().in(this);
				for (var i = 0; i < this.tabList.length; i++) {
					queryTabSize.select('#' + this.tabList[i].id).boundingClientRect();
				}
				queryTabSize.exec(rects => {
					rects.forEach((rect) => {
						this.tabListSize[rect.dataset.id] = rect;
					})
					this.updateIndicator(this.tabListSize[this.tabIndex].left, this.tabListSize[this.tabIndex]
						.width);
					this.switchTab(this.tabIndex);
				});
				// #endif

				// #ifdef MP-WEIXIN || H5 || MP-QQ
				uni.createSelectorQuery().in(this).select('.tab-view').fields({
					dataset: true,
					size: true,
				}, (res) => {
					this.swiperWidth = res.width;
				}).exec();
				uni.createSelectorQuery().in(this).selectAll('.uni-tab-item').boundingClientRect((rects) => {
					rects.forEach((rect) => {
						this.tabListSize[rect.dataset.id] = rect;
					})
					this.updateIndicator(this.tabListSize[this.tabIndex].left, this.tabListSize[this.tabIndex]
						.width);
				}).exec();
				// #endif
			},

			updateIndicator(left, width) {
				this.indicatorLineLeft = left;
				this.indicatorLineWidth = width;
			},

			switchTab(index) {
				if (this.tabIndex === index) {
					return;
				}
				this.tabIndex = index;
				// #ifdef APP-NVUE
				this.scrollTabTo(index);
				// #endif
				// #ifndef APP-NVUE
				this.scrollInto = this.tabList[index].id;
				// #endif
				// 释放 tabId
				if (this.cacheTab.length > MAX_CACHE_PAGE) {
					let cacheIndex = this.cacheTab[0];
					this.clearTabData(cacheIndex);
					this.cacheTab.splice(0, 1);
				}
			},
			scrollTabTo(index) {
				const el = this.$refs['tabitem' + index][0];
				let offset = 0;
				// TODO fix ios offset
				if (index > 0) {
					offset = this.tabbarWidth / 2 - this.tabListSize[index].width / 2;
					if (this.tabListSize[index].right < this.tabbarWidth / 2) {
						offset = this.tabListSize[0].width;
					}
				}
				dom.scrollToElement(el, {
					offset: -offset
				});
			}
		}
	}
</script>

<style>
	/* #ifndef APP-PLUS */
	page {
		width: 100%;
		min-height: 100%;
		display: flex;
	}

	/* #endif */
	.tabs {
		flex: 1;
		flex-direction: column;
		overflow: hidden;
		background-color: #ffffff;
		/* #ifdef MP-ALIPAY || MP-BAIDU */
		height: 100vh;
		/* #endif */
	}

	.tab-bar {
		width: 750upx;
		height: 84upx;
		flex-direction: row;
		/* #ifndef APP-PLUS */
		white-space: nowrap;
		/* #endif */
	}

	/* #ifndef APP-NVUE */
	.tab-bar ::-webkit-scrollbar {
		display: none;
		width: 0 !important;
		height: 0 !important;
		-webkit-appearance: none;
		background: transparent;
	}

	/* #endif */

	.scroll-view-indicator {
		position: relative;
		height: 2px;
		background-color: transparent;
	}

	.scroll-view-underline {
		position: absolute;
		top: 0;
		bottom: 0;
		width: 0;
		background-color: #007AFF;
	}

	.uni-tab-item {
		/* #ifndef APP-PLUS */
		display: inline-block;
		/* #endif */
		width: 50%;
		flex-wrap: nowrap;
		padding-left: 25px;
		padding-right: 25px;
	}

	.uni-tab-item-title {
		color: #555;
		font-size: 30upx;
		height: 80upx;
		line-height: 80upx;
		flex-wrap: nowrap;
		/* #ifndef APP-PLUS */
		white-space: nowrap;
		/* #endif */
	}

	.uni-tab-item-title-active {
		color: #007AFF;
	}

	.tab-view {
		height: 100%;
		flex: 1;
	}

	.swiper-item {
		flex: 1;
		flex-direction: column;
		background: linear-gradient(180deg, #c4d6ff, #f7f8fa);
	}

	#pop {
		width: 600rpx;
		padding: 40rpx 30rpx;
		border-radius: 16rpx;
		background-color: #fff;
	}
</style>